// pages/cart/cart.js
const app = getApp();
Page({
  /**
  * delBtnWidth: 删除按钮的宽度单位
  * list: 循环的mock数据
  * startX: 收支触摸开始滑动的位置
  */
  data: {
    delBtnWidth: 120,
    cartList: [],
    startX: "",
    AllChecked: false,
    cartEmpty: true,
    checkedCount: 0,
    checkedPrice: 0,
    isLogin: false,
    user: []
  },
  deleteItem (e) {
    wx.showModal({
      title: '',
      content: '是否删除',
      success: (res) => {
        if (res.confirm) {
          const id = e.currentTarget.dataset.id
          const list = this.data.cartList.filter(item => {
            return item.id !== id
          })
          this.setData({
            cartList: list
          })
          if (this.data.cartList.length === 0) {
            this.setData({
              cartEmpty: true
            })
          }
          wx.setStorageSync('cart', this.data.cartList)
        } else if (res.cancel) {
          return
        }
      },
      fail: (res) => {
        wx.showToast({
          title: '删除错误',
        })
      }
    })
    this.setBadge()
    this.checkedAllItems()
  },
  toggleItemChecked (e) {
    const id = e.currentTarget.dataset.id
    const list = this.data.cartList.map(item => {
      if (item.id === id) {
        item.checked = !item.checked
      }
      return item
    })
    this.setData({
      cartList: list
    })
    this.changeAllChecked()
    wx.setStorageSync('cart', this.data.cartList)
    this.checkedAllItems()
  },
  setBadge() {
    const text = this.data.cartList.reduce((result,item) => {
      result += item.count
      return result
    },0)
    wx.setTabBarBadge({
      index: 1,
      text: text.toString()
    })
  },
  changeAllChecked () {
    const length = this.data.cartList.filter(item => item.checked === true).length
    if (length === this.data.cartList.length) {
      this.setData({
        AllChecked: true
      })
    } else {
      this.setData({
        AllChecked: false
      })
    }
    this.checkedAllItems()
  },
  toggleCheckAll () {
    const list = this.data.cartList.map(item => {
      item.checked = !this.data.AllChecked
      return item
    })
    this.setData({
      cartList: list,
      AllChecked: !this.data.AllChecked
    })
    this.checkedAllItems()
    wx.setStorageSync('cart', this.data.cartList)
  },
  checkedAllItems () {
    let cart = this.data.cartList.filter(item => item.checked)
    let totalPrice = 0;
    let totalCount = 0;
    // 循环列表得到每个数据
    for (let i = 0; i < cart.length; i++) {
      // 判断选中计算价格
      if (cart[i].checked) {
        // 所有价格加起来 count_money
        totalPrice += cart[i].count * cart[i].price;
        totalCount += cart[i].count
      }
    }
    // 最后赋值到data中渲染到页面
    this.setData({
      checkedPrice: totalPrice.toFixed(2),
      checkedCount: totalCount
    })
 
  },
  add (e) {
    const id = e.currentTarget.dataset.id
    app.add(id)
    this.setBadge()
  },
  reduce(e) {
    const id = e.currentTarget.dataset.id
    this.setBadge()
    app.reduce(id)
    
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.initEleWidth();  
  },
  onReady: function () {
    // 页面渲染完成
    this.changeAllChecked()
    if (this.data.cartList.length !== 0) {
      this.setData({
        cartEmpty: false
      })
    }
  },
  onShow: function () {
    // 页面显示
    this.setData({
      cartList: app.cart,
      user: app.user
    })
    if (this.data.cartList.length !== 0) {
      this.setData({
        cartEmpty: false
      })
    }
    this.setData({
      user: wx.getStorageSync('user')
    })
    if (this.data.user.length !== 0) {
      this.setData({
        isLogin: false
      })
    } else {
      this.setData({
        isLogin: true
      })
    }
    this.setBadge()
    this.checkedAllItems()
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  touchS: function (e) {
    
    if (e.touches.length == 1) {
      this.setData({
        //设置触摸起始点水平方向位置
        startX: e.touches[0].clientX
      });
    }
  },
  touchM: function (e) {
    if (e.touches.length == 1) {
      //手指移动时水平方向位置
      var moveX = e.touches[0].clientX;
      //手指起始点位置与移动期间的差值
      var disX = this.data.startX - moveX;
      var delBtnWidth = this.data.delBtnWidth;
      var txtStyle = "";
      if (disX == 0 || disX < 0) {//如果移动距离小于等于0，说明向右滑动，文本层位置不变
        txtStyle = "left:0px";
      } else if (disX > 0) {//移动距离大于0，文本层left值等于手指移动距离
        txtStyle = "left:-" + disX + "px";
        if (disX >= delBtnWidth) {
          //控制手指移动距离最大值为删除按钮的宽度
          txtStyle = "left:-" + delBtnWidth + "px";
        }
      }
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = this.data.cartList;
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        cartList: list
      });
    }
  },
  touchE: function (e) {
    if (e.changedTouches.length == 1) {
      //手指移动结束后水平位置
      var endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离
      var disX = this.data.startX - endX;
      var delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      var txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "px" : "left:0px";
      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = this.data.cartList;
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        cartList: list
      });
    }
  },
  //获取元素自适应后的实际宽度
  getEleWidth: function (w) {
    var real = 0;
    try {
      var res = wx.getSystemInfoSync().windowWidth;
      var scale = (750 / 2) / (w / 2);//以宽度750px设计稿做宽度的自适应
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
      // Do something when catch error
    }
  },
  initEleWidth: function () {
    var delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth: delBtnWidth
    });
  }
  // //点击删除按钮事件
  // delItem: function (e) {
  //   //获取列表中要删除项的下标
  //   var index = e.currentTarget.dataset.index;
  //   var list = this.data.list;
  //   //移除列表中下标为index的项
  //   list.splice(index, 1);
  //   //更新列表的状态
  //   this.setData({
  //     list: list
  //   });
  // },
})